package application;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.lanhai.model.Agv;
import com.lanhai.model.ControlArea;
import com.lanhai.model.Guidepost;
import com.lanhai.model.Job;
import com.lanhai.model.MapPath;
import com.lanhai.model.Park;
import com.lanhai.model.Station;
import com.lanhai.model.TrafficWait;
import com.lanhai.utils.DialogUtils;
import com.lanhai.utils.DialogUtils.DialogResponse;
import com.lanhai.utils.HttpUtils;
import com.lanhai.utils.UDPListener4Json;

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import net.sf.json.JSONObject;

public class Main extends Application {
	//private static final Logger logger = Logger.getLogger(Main.class);
	
	private WindowEvent event;
	public Stage mainStage;// 主页面stage
	public Properties ppt;
	public UDPListener4Json ulis4Json;
	public ExecutorService pool;
	public ExecutorService httpPool;
	public String logo;
	public String borderColor = "#BFBFBF";//线条颜色
	
	public URL testPanelURL;
	public URL settingURL;
	public URL jobListDialogURL;
	public URL sysErrorListDialogURL;
	public URL trafficDialogURL;
	public URL settingPanelURL;
	public URL commandDialogURL;
	
	public String serverUrl;
	public Integer agvType;
	
	public MainAction mainAction;

	/**
	 * AgvMap
	 */
	public Map<Integer, Agv> agvMap;
	
	public Map<Integer, ControlArea> controlAreaMap;
	public List<TrafficWait> waitAgvList;
	public List<Job> jobList;
	/**
	 * 行车线路
	 */
	public Map<String, MapPath> mapPathMap = new HashMap<String, MapPath>();
	public Map<Integer, Guidepost> guidepostMap = new HashMap<Integer, Guidepost>();
	public Map<Integer, Park> parkMap = new HashMap<Integer, Park>();
	public Map<String, Station> stationMap = new HashMap<String, Station>();
	
	public static void main(String[] args) {
		launch(args);
	}

	@Override
	public void start(Stage stage) throws IOException {
		mainStage = stage;
		//mainStage.setMaximized(true);
		//mainStage.setResizable(false);
		testPanelURL = getClass().getClassLoader().getResource("dialog/MyTestPanel.fxml");
		settingURL = getClass().getClassLoader().getResource("dialog/PassPanel.fxml");
		jobListDialogURL= getClass().getClassLoader().getResource("dialog/JobListDialog.fxml");
		sysErrorListDialogURL= getClass().getClassLoader().getResource("dialog/SysErrorListDialog.fxml");
		trafficDialogURL = getClass().getClassLoader().getResource("dialog/TrafficDialog.fxml");
		settingPanelURL = getClass().getClassLoader().getResource("dialog/SettingPanel.fxml");
		commandDialogURL = getClass().getClassLoader().getResource("dialog/CommandListDialog.fxml");
		
		URL fxmlURL = getClass().getResource("main.fxml");
		logo = getClass().getResource("/img/logo.png").toString();
		
		ppt = new Properties();
		InputStream is = Main.class.getClass().getResourceAsStream("/jdbc.properties");
		ppt.load(is);
		
		serverUrl = ppt.getProperty("serverUrl");
		agvType= Integer.valueOf(ppt.getProperty("agvType"));
		
		pool = Executors.newCachedThreadPool();		
		httpPool = Executors.newCachedThreadPool();
		
		/*
		 * 初始化窗体
		 */
		initPage(stage, "蓝海AGV调度系统控制台", logo, fxmlURL);
		
//		cronJob();
		
		UDPListener4Json utils = new UDPListener4Json(mainAction, 8086);
		Thread t = new Thread(utils);
		t.start();
		
//        HttpServer server = HttpServer.create(new InetSocketAddress(8001), 0);    
//        server.createContext("/save", new BasicPostHttpHandler());
//        server.createContext("/test", new BasicPostHttpHandler2());
//        //设置线程执行器
//        server.setExecutor(httpPool);
//        server.start();
	}

	/**
	 * 退出
	 */
	public void exit() {
		DialogUtils.sure("是否确认退出系统控制台?", new DialogResponse() {

			@Override
			public void onOK() {
				System.exit(0);
			}

			@Override
			public void onCancel() {
				
				event.consume();
			}

		}, "退出系统", logo);
	}

	/**
	 * @param stage
	 * @return
	 * @throws IOException
	 */
	public void initPage(Stage stage, String title, String imageURL, URL fxmlURL)
			throws IOException {

		FXMLLoader fxmlLoader = new FXMLLoader(fxmlURL);
		Parent root = fxmlLoader.load();
		
		double width = root.getBoundsInParent().getWidth();
		double height = root.getBoundsInParent().getHeight();
		
		Scene scene = new Scene(root, width, height);
		scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
		stage.setScene(scene);
		stage.setTitle(title);

		stage.getIcons().add(new Image(imageURL));

		// stage.setAlwaysOnTop(true);
		// stage.setResizable(true);
		stage.setMaximized(true);
		stage.show();	
		
		stage.setOnCloseRequest(new EventHandler<WindowEvent>() {

			@Override
			public void handle(WindowEvent event) {
				Main.this.event = event;
				exit();
			}

		});
		
		mainAction = fxmlLoader.getController();
		mainAction.init(Main.this);			
	}
	
	/**
	 * 每秒钟执行一次定时任务
	 */
	int reconnectTime = 1000;//一秒钟
	public void cronJob() {
		Timer timer = new Timer();
		TimerTask timerTask = new TimerTask() {
			public void run() {
				try{
					//mainAction.refreshControlArea();//刷新交管区列表
					mainAction.loadJob();//刷新任务列表
					mainAction.fillAgvData();//刷新AGV列表				
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		};
		timer.schedule(timerTask, 10000, reconnectTime);
	}
	
	/**
	 * 向服务器提交http请求
	 * @param params
	 */
	public JSONObject httpRequest(Map<String, Object> params){
		String url = "http://" + serverUrl + "/" + params.get("path");
		JSONObject jo = HttpUtils.httpPost2Json(url, params);
		if(jo != null){
			String noPopup = params.get("noPopup") + "";
			if(noPopup.equals("null")){
				boolean flag = jo.getBoolean("success");
				if(flag){
					DialogUtils.show("成功发送数据!", "提示", logo);
				}else{
					DialogUtils.show("数据错误!", "提示", logo);
				}				
			}
		}else{
			DialogUtils.show("远程服务器访问失败!", "提示", logo);
		}
		return jo;
	}
	
}
